<script setup lang='tsx' name='Friend'>
import type { FriendShipInfo, Pagination, QueryFriendFrom } from '@/types/views/friend'
import { delFriendApi, friendListApi, userListApi, findChatroomApi, createOneToOneApi, chatDetailByIdApi } from '@/api'
import { ElMessage, type FormInstance, type TableInstance } from 'element-plus';
import { useChatStore } from '@/stores/chat';
import { useUserStore } from '@/stores/user';
const chatStore = useChatStore()
const userStore = useUserStore()
const router = useRouter()

function useFriendListHook() {
    const formRef = ref<FormInstance>()
    const form = reactive<Pagination & QueryFriendFrom>({
        page: 1,
        pageSize: 10,
        nickName: void 0,
        username: void 0,
    })
    const tableRef = ref<TableInstance>()
    const total = ref(0)
    const table = ref<FriendShipInfo[]>([])
    let timer: number | null = null
    const loading = ref(false)
    function getFriendList() {
        if (timer) clearTimeout(timer)
        loading.value = true
        timer = setTimeout(async () => {
            const { data } = await friendListApi(form)
            table.value = data.rows
            total.value = data.total
            loading.value = false
            clearTimeout(timer as number)
        }, 200) as unknown as number

    }
    async function delFriend(row: FriendShipInfo) {
        await ElMessageBox.confirm(`确认删除该${row.nickName}好友吗?`, '删除好友', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }).catch(() => {
            ElMessage.info('已取消删除')
        })
        await delFriendApi(row.id)
        table.value = table.value.filter(item => item.id !== row.id)
        ElMessage.success('删除成功')
    }
    async function goToChat(friendId: number) {
        const { data } = await findChatroomApi({ userId1: userStore.user.id, userId2: friendId })
        console.log(data, '查询结果')
        if (data) {
            chatStore.currentChatroom = data
            router.push('/chat')
        } else {
            const { data: chatroomId } = await createOneToOneApi(friendId)
            const { data: chatroomDetail } = await chatDetailByIdApi(chatroomId)
            chatStore.chatroomList.push(chatroomDetail)
            chatStore.currentChatroom = chatroomDetail.id
            router.push('/chat')
        }
    }
    function reset() {
        formRef.value?.resetFields()
        getFriendList()
    }
    return { tableRef, total, table, formRef, form, loading, getFriendList, reset, delFriend, goToChat }
}
const { tableRef, total, table, formRef, form, loading, getFriendList, reset, delFriend, goToChat } = useFriendListHook()


getFriendList()
onActivated(() => getFriendList())


</script>

<template>
    <div class='friend-container'>
        <el-row :gutter="10">
            <el-col :span="16">
                <el-form ref="formRef" :model="form" label-width="auto">
                    <el-row :gutter="10">
                        <el-col :span="6">
                            <el-form-item label="昵称" prop="nickName">
                                <el-input clearable v-model="form.nickName" placeholder="输入昵称"
                                    size="default"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="账号" prop="username">
                                <el-input clearable v-model="form.username" placeholder="输入账号"
                                    size="default"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="1.5">
                            <el-button type="primary" @click="getFriendList" plain>查询</el-button>
                        </el-col>
                        <el-col :span="1.5">
                            <el-button @click="reset">重置</el-button>
                        </el-col>
                        <el-col :span="1.5">
                            <el-button plain type="success" @click="$router.push('/add-friend')">添加好友</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </el-col>
        </el-row>
        <el-table v-loading="loading" :data="table" stripe style="width: 100%" ref="tableRef"
            :header-cell-style="{ background: `#f5f7fa` }">
            <el-table-column prop="username" label="账号" />
            <el-table-column prop="nickName" label="昵称" />
            <el-table-column prop="headPic" label="头像" />
            <el-table-column prop="userCount" label="操作">
                <template v-slot="{ row }">
                    <el-button text type="primary" size="small" @click="goToChat(row.id)">聊天</el-button>
                    <el-button text type="primary" size="small" @click="delFriend(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-row justify="end" class="mt-20px">
            <el-pagination v-model:current-page="form.page" v-model:page-size="form.pageSize"
                :page-sizes="[10, 15, 20, 25]" :background="true" size="default"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="getFriendList"
                @current-change="getFriendList" />
        </el-row>
    </div>
</template>

<style lang='scss' scoped></style>